package com.eastfair.certificate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.certificate.CertificateCacheKeyBuilder;
import com.eastfair.cache.certificate.CertificateIndexCacheKeyBuilder;
import com.eastfair.certificate.dao.CertificateMapper;
import com.eastfair.certificate.dto.CertificateDTO;
import com.eastfair.certificate.dto.CertificateUserDTO;
import com.eastfair.certificate.dto.FormFieldSubsystemDTO;
import com.eastfair.certificate.entity.Certificate;
import com.eastfair.certificate.entity.CertificateAuth;
import com.eastfair.certificate.entity.CertificateIndex;
import com.eastfair.certificate.entity.CertificateUser;
import com.eastfair.certificate.enumeration.CertificateAuthClassifyEnum;
import com.eastfair.certificate.enumeration.CertificateCertificateTypeEnum;
import com.eastfair.certificate.exceptioncode.CertificateExceptionCode;
import com.eastfair.certificate.service.CertificateAuthService;
import com.eastfair.certificate.service.CertificateService;
import com.eastfair.boot.service.SuperServiceImpl;

import com.eastfair.certificate.service.FormFieldGroupService;
import com.eastfair.certificate.service.FormFieldSubsystemService;
import com.eastfair.certificate.vo.CertificateUserVO;
import com.eastfair.certificate.vo.CertificateVO;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.exception.BizException;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.eastfair.core.base.R.SUCCESS_CODE;

/**
 * <p>
 * 业务实现类
 * 证件设置
 * </p>
 *
 * @author ligang
 * @date 2022-07-23
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class CertificateServiceImpl extends SuperCacheServiceImpl<CertificateMapper, Certificate> implements CertificateService {

    @Autowired
    FormFieldGroupService formFieldGroupService;

    @Autowired
    CertificateAuthService certificateAuthService;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<Certificate> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(Certificate model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        //雪花ID
        if (model.getUseIndexNumber() == null) {
            model.setUseIndexNumber(0);
        }
        if (model.getIndexNumber() == null) {
            model.setIndexNumber(0);
        }
        return R.successDef();
    }

    @Override
    public R<CertificateVO> saveCertificate(CertificateDTO certificateDTO) {
        Certificate certificate = new Certificate();
        BeanUtils.copyProperties(certificateDTO, certificate);
        CertificateDTO certificateDTO1 = new CertificateDTO();
        certificateDTO1.setCertificateType(certificateDTO.getCertificateType());
        certificateDTO1.setExhibitionId(certificateDTO.getExhibitionId());
        certificateDTO1.setIsDeleted(BusinessConstant.NO);
        List<Certificate> certificateList = list(certificateDTO1, null);
        if (!CollectionUtil.isEmpty(certificateList)) {
            throw BizException.wrap(CertificateExceptionCode.CERTIFICATE_EXIT);
        }
        //默认都打开
        List<CertificateAuth> certificateAuthList = certificateAuthService.list();
        //人证不校验
        //车证只制证校验
        if(CertificateCertificateTypeEnum.CAR.eq(certificate.getCertificateType())){
            certificate.setSecondAuthId(certificateAuthList.stream().filter(s -> CertificateAuthClassifyEnum.MOVEOUT.eq(s.getClassify())).map(CertificateAuth::getId).collect(Collectors.toList()).get(0));
        }
//        certificate.setFirstAuthId(certificateAuthList.stream().filter(s -> CertificateAuthClassifyEnum.ARRANGE.eq(s.getClassify())).map(CertificateAuth::getId).collect(Collectors.toList()).get(0));
//        certificate.setSecondAuthId(certificateAuthList.stream().filter(s -> CertificateAuthClassifyEnum.MOVEOUT.eq(s.getClassify())).map(CertificateAuth::getId).collect(Collectors.toList()).get(0));
        save(certificate);
        //复制动态表单
        FormFieldSubsystemDTO formFieldSubsystemDTO = new FormFieldSubsystemDTO();
        formFieldSubsystemDTO.setGroupId(certificateDTO.getFiledGroupId());
        formFieldSubsystemDTO.setRelatedId(certificate.getId());
        R<Boolean> r = formFieldGroupService.copyFormFieldList(formFieldSubsystemDTO);
        return R.success(doToVo(certificate));
    }


    @Override
    public IPage<CertificateVO> pageCertificate(PageParams<CertificateDTO> params) {
        CertificateDTO certificateDTO = params.getModel();
        IPage<Certificate> page = params.buildPage();
        QueryWrapper<Certificate> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(certificateDTO.getCertificateType() != null, Certificate::getCertificateType, certificateDTO.getCertificateType())
//                .eq(StringUtils.isNotBlank(certificateDTO.getName()), Certificate::getName, certificateDTO.getName())
                .eq(certificateDTO.getExhibitionId() != null, Certificate::getExhibitionId, certificateDTO.getExhibitionId())
                .eq(Certificate::getIsDeleted, BusinessConstant.NO);
        //page entity转vo
        IPage<Certificate> certificateUserIPage = page(page, queryWrapper);
        List<CertificateVO> certificateUserVOList = doToVos(certificateUserIPage.getRecords());
        IPage<CertificateVO> certificateUserVOIPage = ConvertUtil.convertIPage(certificateUserIPage, certificateUserVOList);
        return certificateUserVOIPage;
    }


    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<Certificate> list(CertificateDTO modelDTO, List<Long> ids) {
        return ((CertificateService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'certificateType', #args[0]?.certificateType}," +
                            "{'name', #args[0]?.name}," +
                            "{'costMoney', #args[0]?.costMoney}," +
                            "{'overTimeMoney', #args[0]?.overTimeMoney}," +
                            "{'depositMoney', #args[0]?.depositMoney}," +
                            "{'secondAuthId', #args[0]?.secondAuthId}," +
                            "{'firstAuthId', #args[0]?.firstAuthId}," +
                            "{'indexNumber', #args[0]?.indexNumber}," +
                            "{'startTime', #args[0]?.startTime}," +
                            "{'endTime', #args[0]?.endTime}," +
                            "{'filedGroupId', #args[0]?.filedGroupId}," +
                            "{'exhibitionId', #args[0]?.exhibitionId}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<Certificate> listOfCache(CertificateDTO modelDTO, List<Long> ids) {
        //查询
//        QueryWrapper<Certificate> queryWrapper = new QueryWrapper<>();
//        if (modelDTO != null) {
//            queryWrapper.lambda().eq(modelDTO.getCertificateType() != null, Certificate::getCertificateType, modelDTO.getCertificateType());
//            queryWrapper.lambda().eq(StringUtils.isNotBlank(modelDTO.getName()), Certificate::getName, modelDTO.getName());
//            queryWrapper.lambda().eq(modelDTO.getCostMoney() != null, Certificate::getCostMoney, modelDTO.getCostMoney());
//            queryWrapper.lambda().eq(modelDTO.getOverTimeMoney() != null, Certificate::getOverTimeMoney, modelDTO.getOverTimeMoney());
//            queryWrapper.lambda().eq(modelDTO.getDepositMoney() != null, Certificate::getDepositMoney, modelDTO.getDepositMoney());
//            queryWrapper.lambda().eq(modelDTO.getSecondAuthId() != null, Certificate::getSecondAuthId, modelDTO.getSecondAuthId());
//            queryWrapper.lambda().eq(modelDTO.getFirstAuthId() != null, Certificate::getFirstAuthId, modelDTO.getFirstAuthId());
//            queryWrapper.lambda().eq(modelDTO.getIndexNumber() != null, Certificate::getIndexNumber, modelDTO.getIndexNumber());
//            queryWrapper.lambda().eq(modelDTO.getStartTime() != null, Certificate::getStartTime, modelDTO.getStartTime());
//            queryWrapper.lambda().eq(modelDTO.getEndTime() != null, Certificate::getEndTime, modelDTO.getEndTime());
//            queryWrapper.lambda().eq(modelDTO.getFiledGroupId() != null, Certificate::getFiledGroupId, modelDTO.getFiledGroupId());
//            queryWrapper.lambda().eq(modelDTO.getExhibitionId() != null, Certificate::getExhibitionId, modelDTO.getExhibitionId());
//        }
//        if (ids != null && !ids.isEmpty()) {
//            queryWrapper.lambda().in(Certificate::getId, ids);
//        }
//        queryWrapper.lambda().eq(Certificate::getIsDeleted, BusinessConstant.DELETE_NO);
        Certificate certificate = new Certificate();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, certificate);
        }
        QueryWrap<Certificate> wrapper = Wraps.q(certificate);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(Certificate::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(Certificate::getIsDeleted, BusinessConstant.DELETE_NO);
        List<Certificate> modelList = list(wrapper);
        return modelList;
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public CertificateVO doToVo(Certificate model) {
        CertificateVO modelVo = new CertificateVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<CertificateVO> doToVos(List<Certificate> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<CertificateVO> result = new ArrayList<>();
        for (Certificate model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new CertificateCacheKeyBuilder();
    }
}
